# -*- coding: utf-8 -*-
# @Date   : 2021/04/23
# @Author : zhanghengfeng


'''eof
name:申请企业企业强制执行、行政处罚校验
code:R39_EC_EnterpriseEnforcementAdministrativePenaltyCheck_2D_OTO
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import datetime
import re



def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0\
            or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]
    
def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d')
        except:
            return_data = None

    return return_data


def Formate(time):

    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    if len(tmp) == 6:
                        date = datetime.datetime.strptime(tmp,'%Y%m').strftime('%Y-%m-%d')
                    else:
                        date = datetime.datetime.strptime(tmp,'%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date



def R39_EC_EnterpriseEnforcementAdministrativePenaltyCheck_2D_OTO():

    Null = ['', ' ', None, 'nulll', 'Null', 'NULL', '/', '-', '--']
    data = EC_DSJ_2D.get('data')

    EFB = getTable(data,"EFB",1,0)          # 法院信息
    EFC = getTable(data,"EFC",1,0)          # 行政处罚信息
    passList = []
    CrrDate = datetime.datetime.now().date()
    two_years_ago = CrrDate - datetime.timedelta(days=365 * 2)
    three_years_ago = CrrDate - datetime.timedelta(days=365 * 3)
    five_years_ago = CrrDate - datetime.timedelta(days=365 * 5)
    

    if EFB == 0:
        pass
    elif EFB == [{}]:
        passList.append(1)
    else:
#        EF03 = EFB[0].get("EF03")    # 强制执行记录单元
        EF03 = getTable(EFB[0],"EF03",0,1)
        if EF03 == 0:
            pass
        elif EF03 == [{}]:
            passList.append(1)
        else:
            for i in range(len(EF03)):
                EF030R01 = EF03[i].get("EF030R01")  # 立案日期字段值
                if convertDataType(EF030R01, 'date_time') is not None and convertDataType(EF030R01,'date_time').date() < five_years_ago:
                    passList.append(1)
                else:
                    EF030J02 = EF03[i].get("EF030J02")  # 已执行标的金额
                    EF030J01 = EF03[i].get("EF030J01")  # 申请执行标的价值
                    # 若申请执行标的价值（EF030J01)为空，则使用已执行标的金额(EF030J02)进行矩阵判断。
                    penaltyMoney = EF030J01 if isfloat(EF030J01) else EF030J02
                    
                    if penaltyMoney in Null:
                        passList.append(0)
                    else:
                        EF030R01Date = Formate(EF030R01)      # 转化后的时间格式的立案日期  
                        EF030I02Code = EF03[i].get("EF030I02")
                        if EF030R01Date is None or EF030I02Code is None or EF030I02Code == "":
                            passList.append(0)
                        else:
                            if convertDataType(penaltyMoney, 'float') <= 0:
                                passList.append(1)
                            else:
                                EF030R01Date = EF030R01Date.date()
                                if EF030R01Date > datetime.datetime.now().date():
                                    passList.append(0)
                                elif EF030R01Date > two_years_ago:
                                    if convertDataType(penaltyMoney, 'float') >= 6000:
                                        passList.append(0)
                                    else:
                                        passList.append(1)
                                elif EF030R01Date >= three_years_ago and EF030R01Date <= two_years_ago:
                                    if convertDataType(penaltyMoney, 'float') > 15000:
                                        passList.append(0)
                                    else:
                                        passList.append(1)
                                else:
                                    if convertDataType(penaltyMoney, 'float') > 25000:
                                        passList.append(0)
                                    else:
                                        passList.append(1)
                                
                            
                                    
    if EFC == 0:
        pass
    elif EFC == [{}]:
        passList.append(1)
    else:
        EF04 = getTable(EFC[0],"EF04",0,1)
        if EF04 == 0:
            pass
        elif EF04 == [{}]:
            passList.append(1)
        else:
            for i in range(len(EF04)):
                EF040R01 = EF04[i].get("EF040R01")  # 立案日期字段值
                if convertDataType(EF040R01, 'date_time') is not None and convertDataType(EF040R01,'date_time').date() < five_years_ago:
                    passList.append(1)
                else:
                    EF040J01 = EF04[i].get("EF040J01")  # 处罚金额
                    
                    if EF040J01 in Null:
                        passList.append(0)
                    else:
                        EF040R01Date = Formate(EF040R01)      # 转化后的时间格式的立案日期  
                        if EF040R01Date is None:
                            passList.append(0)
                        else:
                            if convertDataType(EF040J01, 'float') <= 0:
                                passList.append(1)
                            else:
                                EF040R01Date = EF040R01Date.date()
                                if EF040R01Date > datetime.datetime.now().date():
                                    passList.append(0)
                                elif EF040R01Date > two_years_ago:
                                    if convertDataType(EF040J01, 'float') >= 6000:
                                        passList.append(0)
                                    else:
                                        passList.append(1)
                                elif EF040R01Date >= three_years_ago and EF040R01Date <= two_years_ago:
                                    if convertDataType(EF040J01, 'float') > 15000:
                                        passList.append(0)
                                    else:
                                        passList.append(1)
                                else:
                                    if convertDataType(EF040J01, 'float') > 25000:
                                        passList.append(0)
                                    else:
                                        passList.append(1)

    # 逻辑判断
    passSet = list(set(passList))
    if 0 in passSet:
        Factor = 0
    else:
        Factor = 1

    return Factor


result = R39_EC_EnterpriseEnforcementAdministrativePenaltyCheck_2D_OTO()
